<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onChangeType="onChangeType"
          @onFind="onFind"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="false" @onAddData="onAddData"
          :delectData="true" @onDelectData="onDelectData"
          :optData="optText" @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <!-- <a-button type="primary" icon="vertical-align-bottom" size="small"> 自定义按钮 </a-button> -->
            <!-- <im-export></im-export> -->
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          :renderStateByField="renderStateByField"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
        >
        </a-list-table>
      </template>
    </table-layout>
     <saleOrderModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <auditModal ref="auditModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import saleOrderModal from './saleOrderModal'
import viewModal from './viewModal'
import auditModal from './auditModal'
import {columns} from './dataConfig'
import {
  getByConditions,
  getByConditionsCount,
  deleteInfo
} from './saleOrder'

const renderStateByField=['saleOrderState']
let links=['zhuCezh','pinMing','gongYinsmc']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewModal,
    auditModal,
    saleOrderModal
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      links:links,
      renderStateByField:renderStateByField,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [ 
        { label: '采购类型', name: 'saletype', type: 'dicselect',dicName:'purType', placeholder: '采购类型' },
        { label: '客户名称', name: 'customerPid', type: 'customer', placeholder: '客户名称' },
        { label: '销售单号', name: 'pid', type: 'saleOrderSelect', placeholder: '销售单号' },
        { label: '客户订单号', name: 'purOrderNo', type: 'input', placeholder: '客户订单号' },
        { label: '订单状态', name: 'saleOrderState', type: 'dicselect',dicName:'saleOrderStatus', placeholder: '订单状态' },
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        pid: null,
        customerPid: null,
        saletype:null,
        purOrderNo:null,
        saleOrderState:null
      },
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '批量确认',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false
    }
  },
  computed: {},
  watch: {
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
        handler: function (val, oldVal) {
          //created事件触发的函数可以在这里写... 
          console.log(this.$route); 
          if (!this.$route.meta.keepAlive) {
            if(this.$route.meta.zhuangTai){
              // this.q_formDatas.zhuangTai=this.$route.meta.zhuangTai
              this.q_formDatas.zhuangTai=null
            }
            this.getTotal()
            this.getList(this.q_formDatas)
            
          }else{//如果keepalive==true
            console.log(this.$route.params.isBack);
            if (!this.$route.params.isBack) {
              this.getTotal()
              this.getList(this.q_formDatas)
            }
            this.isJump=false
          }
          
          
        },
        deep: true,
        immediate:true
    }
  },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    // this.getTotal()
    // this.getList(this.q_formDatas)
    
  },
  methods: {
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    formatParms(){
      let sbdata=JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        console.log(key,sbdata[key]);
        if (!sbdata[key]){
          sbdata[key]=null  
        }
        
        if (key=='purOrderNo' || key=='manufacturerZh') {
          if (sbdata[key]==null) {
            sbdata[key]=`%%`
          }else{
            sbdata[key]=`%${sbdata[key]}%`
          }
          
        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn=['订单明细']
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            if (item.saleOrderState==this.appState.saleOrderState.unConfirm.code) {
              actionBtn=['确认','订单明细']
            }else{
              actionBtn=['订单明细']
            }
            listdata.push({
               key: item.pid,
               action:actionBtn,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      if (text == '订单明细') {
        this.$refs.viewModal.showModal(record.pid,record)
        // this.showConfirm(record)
      } else if (text == '确认') { 
        // this.showConfirm(record,'1')
        this.$refs.auditModal.editModal(record.pid, record)
      }
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      switch (name) {
        case 'pid': 
          if (!val[0]) {
            this.q_formDatas.pid=null
          }
          this.onFind ()
          break 
        case 'customerPid':
          if (!val) {
            this.q_formDatas.customerPid=null
          }
          this.onFind ()
          break
        case 'saletype':
          if (!val) {
            this.q_formDatas.saletype=null
          }
          this.onFind ()
          break
        case 'saleOrderState':
          if (!val) {
            this.q_formDatas.saleOrderState=null
          }
          this.onFind ()
          break
      }
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='zhuCezh'){
        this.isJump=true
        this.$router.push({ 
          name: 'registerLicensePassed', 
          params: {
            isJump:this.isJump ,
            pathName:this.$route.name,
            zhengZhaohm: record.zhuCezh
          } 
        })
      }else if(link=='pinMing'){
        this.$refs.viewModal.showModal(record.pid,record)
      }else if(link=='gongYinsmc'){
        this.isJump=true
        this.$router.push({ 
          name: 'supplierInfo', 
          params: {
            isJump:this.isJump ,
            pathName:this.$route.name,
            keHuPid: record.gongYinsOrgPid 
          } 
        })
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的商品', duration: 3 })
      }
    },
    showDelConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'采购订单'+item.data.saleOrderNo+ '删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'采购订单'+item.data.saleOrderNo+ '删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async delOrder(val){
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已处理的订单，请选择未处理的订单', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要处理的订单', duration: 3 })
      }
    }
  },
}
</script>

<style>
</style>